﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RSSReader.MobileClient.Resources;
using RSSReader.MobileClient.ViewModel;
using RSSReader.MobileClient.View;
using RSSReader.MobileClient.Model;
using RSSReader.MobileClient.WCFWebRoleService;
using System.Threading.Tasks;
using System.Net.NetworkInformation;

namespace RSSReader.MobileClient
{
    public partial class MainPage : PhoneApplicationPage
    {
        private UserViewModel Uservm;
        DataDistributorClient client = new DataDistributorClient();

        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            Uservm = new UserViewModel();

            if (Uservm.Usr.UserId != null)
            {
                Uservm.GetSavedUserId();
                NavigationService.Navigate(new Uri("/FeedSelectorPage.xaml", UriKind.Relative));
            }
        }

        public void CheckUser_Click(object sender, RoutedEventArgs e)
        {
            //NavigationService.Navigate(new Uri("/ArticleSelector.xaml", UriKind.Relative));

            var asyncMgr = new AsyncDataManager(() =>
            {
                if (Uservm.Usr.UserId != null)
                {
                    App.UserId = Uservm.Usr.UserId;
                    NavigationService.Navigate(new Uri("/FeedSelectorPage.xaml", UriKind.Relative));
                }
                else
                    MessageBox.Show("Invalid login and/or password");
            });
            Uservm.GetUserId(asyncMgr, Username.Text, Password.Text);
            asyncMgr.SetExpectation("GotUserId");
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);

            if (e.Uri.ToString() == "/FeedSelectorPage.xaml")
            {
                Uservm.SaveUserId();

                if (this.State.ContainsKey("UserId"))
                {
                    this.State["UserId"] = App.UserId;
                }
                else
                {
                    this.State.Add("UserId", App.UserId);
                }
            }
        }

        private void CreateUser_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreateUserPage.xaml", UriKind.Relative));
        }
    }
}